import uuid
import datetime
from django.http import HttpResponse,JsonResponse
from django.shortcuts import render,redirect
from web.forms.account import RegisterModelForm,SendSmsForm,LoginSmsForm,LoginForm
from web import models
from django.db.models import Q

# 账户相关功能：注册、短信、登录、注销
def hello(request):
    return HttpResponse('hello word!!!')

def register(request):
    """注册"""
    if request.method == "GET": 
        form = RegisterModelForm()
        return render(request,"register.html",{"form":form})

    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 验证通过，写入数据库(直接进行保存的话，密码是明文,所以需要对密码加密)
        # 用户创建成功表中新建一条交易记录数据

        # 方式一
        instance = form.save()
       
        policy_object = models.PricePolicy.objects.filter(catergory = 1,title ='个人免费版').first()
        models.Transaction.objects.create(
            status = 2,
            order = str(uuid.uuid4()),
            user = instance,
            price_policy = policy_object,
            count = 0,
            price = 0,
            start_datetime = datetime.datetime.now()
        )
        
        # 方式二
        return JsonResponse({'status':True,'data':'/login/'})
 
    return JsonResponse({'status':False,'error':form.errors})

def send_sms(request):
    """发送短信"""
   
    form = SendSmsForm(request,data=request.GET)
    # 校验手机号：不能为空、格式是否正确
    if form.is_valid():
        return JsonResponse({'status':True})
   
    return JsonResponse({'status':False,'error':form.errors})

def login_sms(request):
    """短信验证登录"""
    if request.method == "GET":
        form = LoginSmsForm()
        return render(request,'login_sms.html',{'form':form})
    
    form = LoginSmsForm(request.POST)
    if form.is_valid():
        # 用户输入正确，登录成功
        usr_obj = form.cleaned_data['mobile_phone']
        # 用户信息放入session中
        request.session['usr_id'] = usr_obj.id
        request.session.set_expiry(60*60*24*14)

        return JsonResponse({'status':True,'data':'/index/'})
    return JsonResponse({'status':False,'error':form.errors})

def login(request):
    """用户密码登录"""
    if request.method == "GET":
        form = LoginForm(request)
        return render(request,'login.html',{'form':form})

    form = LoginForm(request,data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']

        # 用户名和密码登录
        # usr_obj = models.Userinfo.objects.filter(username=username,password=password).first()
    
        # 手机号或邮箱登录    
        usr_obj = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(password=password).first()
        print('usr_obj:',usr_obj)
        if usr_obj:
            # 登录成功为止1
            request.session['usr_id'] = usr_obj.id
            request.session.set_expiry(60*60*24*14)

            return redirect('web:index')
        
        form.add_error('username', '用户名或邮箱错误')
    return render(request,'login.html',{'form':form})

def image_code(request):
    """生成图片验证码"""
    from utils.image_code import check_code
    from io import BytesIO
    image_obj,code = check_code()

    # 把生成的验证码存到session中
    request.session['code'] = code
    # 设置session验证码失效时间位60s
    request.session.set_expiry(60)
    # 把图片写入内存中
    stream = BytesIO()
    image_obj.save(stream, 'png')

    return HttpResponse(stream.getvalue())

def logout(request):
    # 把session中的数据清空
    request.session.flush()

    return redirect('web:index')